package com.maibow.util.weixin;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpStatus;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.maibow.entity.weixin.AccessToken;
import com.maibow.entity.weixin.WeixinQRCode;
import com.maibow.entity.weixin.WeixinTicket;
import com.maibow.util.CommonConstants;
import com.maibow.util.DateUtil;
import com.maibow.util.FileUpload;
import com.maibow.util.HttpRequestUtils;
import com.maibow.util.Logger;
import com.maibow.util.PathUtil;
import com.maibow.util.UuidUtil;

public class WeixinQRCodeUtil {
    protected Logger logger = Logger.getLogger(this.getClass());

    /**
     * 
     * getTicket(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param accessToken
     * 标记：@param jsonParam
     * 标记：@return
     * 标记：@throws Exception
     * 标记：@throws IOException
     * 返回值：WeixinTicket
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    public WeixinTicket getTicket(String accessToken, JSONObject jsonParam) throws Exception, IOException {
        WeixinTicket weixinTicket = new WeixinTicket();
        try {
            String requestUrl = WeixinConstants.GET_WEIXINTICKET_QRCODE_URL.replace("ACCESS_TOKEN", accessToken);
            JSONObject json = HttpRequestUtils.httpPost(requestUrl, jsonParam);
            // 如果请求成功
            if (null != json) {
                try {
                    weixinTicket.setTicket(json.get("ticket").toString());
                    weixinTicket.setExpiresIn(Integer.valueOf(json.get("expires_in").toString()));
                    logger.debug("ticket================ " + weixinTicket.getTicket());
                } catch (Exception e) {
                    accessToken = null;
                    // 获取ticket失败
                    logger.debug("获取ticket失败 errcode:{} errmsg:{}" + json.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return weixinTicket;
    }

    /**
     * 
     * getQRCode(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param ticket
     * 标记：@param number
     * 返回值：void
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    public String getQRCode(String ticket, long number) {
        WeixinQRCode weixinQRCode = new WeixinQRCode();
        String requestUrl = WeixinConstants.GET_WEIXIN_QRCODE_URL.replace("TICKET", ticket);
        HttpClient client = new DefaultHttpClient();
        try {
            HttpGet request = new HttpGet(requestUrl);
            HttpResponse response = client.execute(request);

            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                weixinQRCode.setUrl(requestUrl);
            }
        } catch (IOException e1) {
            weixinQRCode = null;
            e1.printStackTrace();
        }

        String imageUrl = null;
        if (null != weixinQRCode.getUrl()) {
            String ffile = DateUtil.getDays(), fileName = "";

            String imageurlstr = weixinQRCode.getUrl();

            // 先将base64转换成流
            InputStream inputStream = FileUpload.returnBitMap(imageurlstr);

            // 上传图片文件名
            String key = UuidUtil.get32UUID() + "_" + number;

            // 再将流转成webp存储到本地
            fileName = PathUtil.getUploadImagePath() + CommonConstants.FILEPATHIMG + ffile + "_wxqrcode/" + key + ".png"; // 文件上传路径
            File file = FileUpload.processPng(inputStream, fileName);
            if (file.exists()) {
                logger.debug("文件路径===================== " + file.getAbsolutePath());
                imageUrl = CommonConstants.FILEPATHIMG + ffile + "_wxqrcode/" + key + ".png";
            }
        }
        return imageUrl;
    }

    /**
     * 
     * main(这里用一句话描述这个方法的作用)
     * (这里描述这个方法适用条件 – 可选)
     * 标记：@param args
     * 返回值：void
     * 作者：吴比(Wubi)
     * 
     * @exception
     * @since 1.0.0
     */
    public static void main(String[] args) {
        WeixinQRCodeUtil util = new WeixinQRCodeUtil();
        WeixinUtil weixinUtil = new WeixinUtil();
        try {
            AccessToken accessToken = weixinUtil.getAccessTokenV3(WeixinConstants.CHUXIAN_PARTY_APPID, WeixinConstants.CHUXIAN_PARTY_SECRET);
            String token = accessToken.getAccessToken();
            JSONObject jsonParam = new JSONObject();
            Map<String, Object> map = new HashMap<String, Object>();
            // 永久二维码
            // map.put("action_name",
            // "QR_LIMIT_STR_SCENE");
            // 临时二维码
            map.put("action_name", "QR_SCENE");
            map.put("expire_seconds", 2592000);
            Map<String, Object> actionInfoMap = new HashMap<String, Object>();

            Map<String, Object> sceneMap = new HashMap<String, Object>();
            int no = 1004;
            sceneMap.put("scene_id", no);
            // 只有永久二维码才支持
            // sceneMap.put("scene_str", no);

            actionInfoMap.put("scene", sceneMap);
            map.put("action_info", actionInfoMap);
            jsonParam.putAll(map);
            WeixinTicket ticket = util.getTicket(token, jsonParam);
            if (null != ticket.getTicket()) {
                util.getQRCode(ticket.getTicket(), no);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
